package com.example.devtool.generate.util;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.example.devtool.generate.controller.request.GenerateRequest;
import java.util.Collections;

/**
 * @author zhuliangxuan
 * @date 2022/5/21 22:55
 */
public class GenerateUtil {

    /**
     * mybatis自动生成
     * @param request 请求
     */
    public static void mybatisGenerate(GenerateRequest request) {
        FastAutoGenerator.create(request.getJdbcUrl(), request.getUsername(), request.getPassword())
                .globalConfig(builder -> {
                    builder.author(request.getAuthor());
                    if (request.isSwagger()) {
                        builder.enableSwagger();
                    }
                    builder.outputDir(request.getProjectDir());
                })
                .packageConfig(builder -> {
                    builder.parent(request.getParent())
                            .moduleName(request.getModuleName())
                            .pathInfo(Collections.singletonMap(OutputFile.mapper, request.getMapperDir()));
                })
                .strategyConfig(builder -> {
                    if (request.isIncludeMode()) {
                        builder.addInclude(request.getIncludeList());
                    }else if (request.isExcludeMode()) {
                        builder.addExclude(request.getExcludeList());
                    }
                    if (!CollectionUtil.isEmpty(request.getTablePrefix())) {
                        builder.addTablePrefix(request.getTablePrefix());
                    }
                    if (!CollectionUtil.isEmpty(request.getTableSuffix())) {
                        builder.addTableSuffix(request.getTableSuffix());
                    }
                })
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }
}
